<?php

/**
 * 软件包管理
 *
 * @author dalei.chen
 */

require_once 'CommonController.php';

class Admin_SourceAppController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_sourceAppModel = new Application_Model_SourceApp();
        $this->_ppModel = new Application_Model_PartnerProduct();
        $this->_mModel = new Application_Model_Member();  
        $this->_memberSourceApplyModel = new Application_Model_MemberSourceApply();
        $this->_productModel = new Application_Model_PartnerProduct();     
        $this->view->title = "管理中心";
    }

    /**
     * 软件包列表 - 管理员
     * 
     */
    public function indexAdminAction()
    {
        $this->indexData();
        $this->view->backAction = 'index-admin';
        $this->view->suffix = 'admin';
        $this->renderScript('source-app/index-admin.php');
        
    }
    
    
    /**
     * 软件包列表 - 渠道经理
     * 
     */
    public function indexManagerAction()
    {
        $wheres[]=" sa.`status`=3 ";
        $this->indexData($wheres);
        $this->view->backAction = 'index-manager';
        $this->view->suffix = 'manager';
        $this->renderScript('source-app/index-manager.php');
        
    }
    
    /**
     * 软件包列表 - 上传人员
     * 
     */
    public function indexUploadAction()
    {
        $this->view->backAction = 'index-upload';
        $this->view->suffix = 'upload';
        $this->indexData();
        
    }
    
    /**
     * 软件包列表 - 测试人员
     * 
     */
    public function indexTestAction()
    {
        
        $this->view->backAction = 'index-test';
        $this->view->suffix = 'test';
        $this->indexData();
        
    }
    
    /**
     * 为列表页面数据收集的子函数
     * Enter description here ...
     */
    public function indexData($wheres=array())
    {
        //获取源ID
        $this->view->memberSourceApplyId=$memberSourceApplyId=intval($this->_request->get('memberSourceApplyId'));
        $configs=$this->_configs;
        $this->view->configs=$configs;
        
        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        //设置URL模板
        $urls = array();
        
        $wheres[]= " memberSourceApplyId = {$memberSourceApplyId} ";
        $wheres[]= " sa.productCode = pp.code ";       
        $wheres[]= " sa.memberCode = m.code";
        
       
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        
        $sql = "select sa.id as `id`,sa.*,
        pp.name as `productName`,
        m.name as `memberName` 
        from `{$this->_sourceAppModel->getTableName()}` as sa,
        `{$this->_ppModel->getTableName()}` as pp,
        `{$this->_mModel->getTableName()}` as m 
        {$where} 
        order by sa.id asc";

        
        
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();
        
        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $dbPaginator->getRows();
        
        //创建FTP连接
        $ftpModel = new Application_Model_Ftp($this->_configs['project']['ftp']);
        
        //createDirectory($testFilePath);
        $i=0;
        foreach($this->view->rows as $row) {
             //保存应有的测试文件路径
            $should_test_url = $this->_sourceAppModel->getShouldTestUrl($row['id']);
            $this->view->rows[$i]['should_test_url']=$should_test_url;
            //收取所有测试路径下文件列表
            $testFileFolder = $this->_sourceAppModel->getTestFilePath($row['id']);
            $testFilePath = $testFileFolder.'/'.$this->_sourceAppModel->getTestFileName($row['id']);
            (array) $files = $ftpModel->listFiles($testFileFolder);

            $files = $files !== false ? $files : array();
            
            $flag=0;
            $j=0;
            foreach($files as $file) {
                $filename=substr($file,0,strpos($file, '.'));
                
                if($filename==substr($testFilePath,strrpos($testFilePath,'/')+1)) {
                    $flag =1 ;
                    $file_pos=$j;
                    break ;
                }
                ++$j;
                
            }
           
            
           
            if($flag) {
                //存在测试文件
                $this->view->rows[$i]['test_url']=$testFileFolder.'/'.$files[$file_pos];
                
                
            } else {
                //不存在测试文件
                $this->view->rows[$i]['test_url']='';
            }
            
            ++$i;
            
        }

        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
    }
    
    /**
     * 批量移动测试软件包到生产路径
     */
    public function moveMulTestAppAction()
    {
        $backAction = $this->_request->get('backAction');
        if ($this->_request->isPost()) {
            
            $ids= $this->_request->getPost('selectId');
            
            if (is_array($ids)) {
                foreach($ids as $id) {
                    $row = $this->_sourceAppModel->fetchRow("`id` = {$id}");
                    if($row['status']==2) {
                        $this->_sourceAppModel->moveOneTestApp($row);
                        $this->_sourceAppModel->update(array('status'=>3), "id={$id}");
                        $memberSourceApplyId=$row['memberSourceApplyId'];
                    }              
                }
            }
        }
        $backUrl = urldecode($this->view->projectUrl(array('action'=>$backAction,'memberSourceApplyId'=>$memberSourceApplyId)));
        redirect($backUrl);
        exit;
    }
    

    /**
     * 批量修改测试软件包的状态
     */
    public function updateMulStatusAction()
    {
        $memberSourceApplyId=$this->_request->get('memberSourceApplyId');
        $backAction = $this->_request->get('backAction');
        
        if ($this->_request->isPost()) {
            
            $filter = new Zend_Filter_StripTags();
            
            $ids= $this->_request->getPost('selectId');
            
            if (is_array($ids)) {
                foreach($ids as $id) {
                    $row = $this->_sourceAppModel->fetchRow("`id` = {$id}");
                    $new_status = intval($filter->filter(trim($this->_request->getPost('status_'.$id))));
                    if($row['status']!=$new_status) { 
                                 
                      if($new_status==3 ) {
                            //移动测试软件包到正式路径
                            $this->_sourceAppModel->moveOneTestApp($row);                            
                        } elseif($new_status==4 || $new_status==1) {
                            //驳回测试软件包
                            $this->_sourceAppModel->moveOneAppTest($row);
                        }                        
                        $this->_sourceAppModel->update(array('status'=>$new_status,'testUserName'=>$this->_currentUserRow['userName'],'testTime'=>date('Y-m-d H:i:s'),'testNotes'=>''), "id={$id}");
                    }
                }
            }
        }
        $backUrl = urldecode($this->view->projectUrl(array('action'=>$backAction,'memberSourceApplyId'=>$memberSourceApplyId)));
        redirect($backUrl);
        exit;
    }
        
    /**
     * 上传测试软件-上传人员
     * Enter description here ...
     */
    public function uploadTestUploadAction()
    {
        $this->uploadTest();
        $this->view->suffix = "upload";
        $this->renderScript('source-app/upload-test.php');
    }
    
     /**
     * 上传测试软件
     */
    public function uploadTest()
    {
        $memberSourceApplyId = intval($this->view->memberSourceApplyId = intval($this->_request->get('memberSourceApplyId')));
        $this->view->id = $id = intval($this->_request->get('id'));
        $this->view->backAction = $backAction = $this->_request->get('backAction');
        $backUrl = $this->view->projectUrl(array('action'=>$backAction,'memberSourceApplyId'=>$memberSourceApplyId));
        
         if (!empty($_FILES['path']['name'])) {
             
                 //上传到本地服务器
                 $uploaddir =$this->_configs['project']['fileSavePath'];
                 $fileBaseName =  basename($_FILES['path']['name']);
                 $extname = substr($_FILES['path']['name'],strrpos($_FILES['path']['name'], "."));
                $uploadfile = $uploaddir .'/'.$this->_sourceAppModel->getTestFileName($id).$extname;

                if (move_uploaded_file($_FILES['path']['tmp_name'], $uploadfile)) {
                   //本地上传成功
                   //将本地文件上传到FTP上面
                   $ftpModel = new Application_Model_Ftp($this->_configs['project']['ftp']);
                   $ftpFilePath = $this->_sourceAppModel->getTestFilePath($id).'/'.$this->_sourceAppModel->getTestFileName($id).$extname;
                   $localFilePath = $uploadfile;
                
                   @$ftpModel->mkdir($this->_sourceAppModel->getTestFilePath($id),"0777");
                   $ftpModel->upload($ftpFilePath,$localFilePath);
                  
                   //上传成功
                   //切换测试文件上传完毕后的状态
                   $this->_sourceAppModel->update(array('status'=>2), "id={$id}");
                   //切换member_source_apply表的状态为4
                   $this->_memberSourceApplyModel->update(array('status'=>4), "id={$memberSourceApplyId}");
                   
                   //删除本地文件
                   //@unlink($localFilePath);
            
                   echo $this->view->message('上传成功！', $backUrl);
                      exit;
                } else {
                    //本地上传失败
                    echo "Possible file upload attack!\n";
                }

            }
     }
     /**
      * FTP移动操作
      */
     public function ftpRelationAction()
     {
         $id=$this->_request->get('id');
         if (empty($id)) {
            exit('没有传递ID参数');
         }
         $memberSourceApplyId = $this->_request->get('memberSourceApplyId');
         
         //获取文件目录
         $testFileFolder = $this->_sourceAppModel->getTestFilePath($id);
         $testFileName = $this->_sourceAppModel->getTestFileName($id);
         //判断文件存在与否
         //创建FTP连接
        $ftpModel = new Application_Model_Ftp($this->_configs['project']['ftp']);
        
         (array)$files = $ftpModel->listFiles($testFileFolder);
         
          $files = $files !== false ? $files : array();
            
            $flag=0;
            $j=0;
            foreach($files as $file) {
                $filename=substr($file,0,strpos($file, '.'));
                
                if($filename==$testFileName) {
                    $flag =1 ;
                    $file_pos=$j;
                    break ;
                }
                ++$j;
            }
            
           
            if($flag) {
                //文件存在;
                //设置状态为2
                $this->_sourceAppModel->update(array('status'=>2), "`id`={$id}");
                //切换member_source_apply表的状态为4
                $this->_memberSourceApplyModel->update(array('status'=>4), "id={$memberSourceApplyId}");
                
                $backUrl=$this->view->projectUrl(array('action'=>'index-upload',
                'memberSourceApplyId'=>$memberSourceApplyId));
                echo $this->view->message('关联文件成功！', $backUrl) ;
            }
            else {
                //文件不存在
                 $backUrl=$this->view->projectUrl(array('action'=>'upload-test-upload',
                'memberSourceApplyId'=>$memberSourceApplyId,'id'=>$id,'backAction'=>'index-upload'));
                 echo $this->view->message('关联文件不存在！', $backUrl) ;
            }
            
            exit;
            
     }
     
     /**
      * 测试评价软件包 - 测试员
      */
     public function testCommentTestAction()
     {
         $this->view->suffix = "test";
         $this->testComment();
         $this->renderScript('source-app/test-comment.php');
     }
     /**
      * 测试评价软件包
      * 
      */
     public function testComment()
     {
    	
         $id = intval($this->_request->get('id'));
         $this->view->backAction = $backAction = $this->_request->get('backAction');
        if (empty($id)) {
             throw new Exception('Invalid params!');
        }
        
        $this->view->row = $this->_sourceAppModel->fetchRow("`id` = {$id}"); 
        $backUrl = urldecode($this->view->projectUrl(array('action'=>$backAction,'memberSourceApplyId'=>$this->view->row['memberSourceApplyId'])));
        
        if ($this->_request->isPost()) {
            $row = array();
            $filter = new Zend_Filter_StripTags();
            $row['testUserName'] = $this->_currentUserRow['userName'];
            $row['status'] = intval($this->_request->getPost('status'));
            $row['testNotes'] = $filter->filter(trim($this->_request->getPost('testNotes')));
            $row['testTime'] = date('Y-m-d H:i:s');
            
            if(empty($row['status'])) {
                 echo $this->view->message('必须选择测试结果，请重新填写！') ;
                exit;
            }
            
            

            //修改数据库信息
            $this->_sourceAppModel->update($row, "`id` = {$id}");
            
            if($row['status']==3) {
                //移动测试软件包到正式路径
                $this->_sourceAppModel->moveOneTestApp( $this->view->row );
                //检测是否所有测试软件包已经测试通过
                
                if($this->_sourceAppModel->checkAppOkByMemberSourceApplyId($this->view->row['memberSourceApplyId'])) {
                    $this->_memberSourceApplyModel->update(array('status'=>5), "id={$this->view->row['memberSourceApplyId']}");
                    //发送邮件到指定的渠道经理
                    $to=$this->_memberSourceApplyModel->getManagerList($id);
	                if(!$to) {
			               echo $this->view->message('邮件发送失败！请查看相关用户是否填写邮件地址。');
			               exit;
		            }else {
		                 	
		                     $rowNew = $this->_memberSourceApplyModel->fetchRow("id={$this->view->row['memberSourceApplyId']}");                     
		                     $productName = $this->_productModel->getProductNameByProductCode($rowNew['productCode']);
		                     $subject = $productName."Source软件包测试通过自动提醒";
		                     $testUser =$rowNew['appTestUserName'];
		                     //获取审核时间
		                    $checkTime = $rowNew['checkTime'];
		                    //获取申请软件包的ID
		                    $memberSourceAppId = $rowNew['id'];
		                    
		                        $message = "
		                        <html>
		                        <head>
		                        <title>".$subject."</title>
		                        </head>
		                        <body>
		                        <p>你好</p>
		                        
		                        <p>".$testUser."完成了打包申请的测试，并且在".$checkTime."通过审核。</p>
		                        
		                        <p>请您确定以哪种方式将安装包提交到渠道。申请的渠道应用编号是: ".$memberSourceAppId."</p>
		                        
		                        <p>注：以上邮件为系统自动发送，请勿回复，如有疑问请与".$testUser."联系。</p>
		                        
		                        </body>
		                        </html>
		                        ";
		                    $mailModel = new Application_Model_Mail();
		                    
		                    
		                    $mailModel->sendMul($to, $subject, $message);
		                    
		                    
		                    if ($mailModel->getSendStaus() != 0) {
		                        echo $mailModel->getSendInfo();
		                        exit();
		                    }
		            }
                }
                
                
            } elseif($row['status']==4 && $this->view->row['status']!=4) {
                //驳回测试软件包
                $this->_sourceAppModel->moveOneAppTest( $this->view->row );
                
                //将member——Source——Apply表的状态修改成4
                $this->_memberSourceApplyModel->update(array('status'=>4), "id={$this->view->row['memberSourceApplyId']}");
            }

            echo $this->view->message('操作成功！', $backUrl) ;
            exit;
        }         
        
     }
    
}